import Vue from 'vue'
import Vuex, {
  Store
} from 'vuex'
import getapi from "@/api/ajax"
import {
  Toast
} from 'vant'; //轻提示
Vue.use(Vuex)
import { //Localstorage
  getUser,
  getToken
} from "@/utils/token.js";
//token验证
import loginApi from '@/api/userget.js'
export default new Vuex.Store({
  state: {
    show: false, //loading
    cartnum: 0, //购物车商品总量
    username: '',
    token: ''
  },
  mutations: {
    setshow(state, isok) {
      state.show = isok;
    },
    setcartnum(state, num) {
      state.cartnum = num;
    },
    setusername(state, data) {
      let {
        name,
        token
      } = data;
      state.username = name;
      state.token = token;
    }
  },
  actions: {
    //loading状态
    show(context, isok) {
      context.commit('setshow', isok);
    },
    //购物车商品总量
    async cartnum(context) { //购物车商品总量
      try {
        let n = await getapi.getdata("shopcart/CartInfo/GetCartNum", "");
        let num = n.data.Data.Num;
        context.commit('setcartnum', num);
      } catch (err) {
        console.log(err);
      }
    },
    // 添加购物车
    async addcard(context, i) {
      let body = {
        Commoditys: [{
          CommodityAmount: i.num, //商品数量
          CommodityId: i.id, //ID
          CommodityType: 1,
          LimitCount: 20,
          PromotionId: ""
        }],
        SourceType: 2
      };
      try {
        let n = await getapi.getdata("shopcart/CartOperation/AddCart", body);
        if (n.status == 200) {
          if (n.data.Message) {
            Toast(n.data.Message);
          } else {
            Toast("添加购物车成功");
          }
        }
      } catch (err) {
        console.log(err);
      }
      context.dispatch('cartnum'); //刷新购物车数量
    },
    //登录信息
    username(context) {
      let name = getUser();
      let token = getToken();
      let data = {
        name: name,
        token: token
      }
      context.commit("setusername", data)
    },
    //token验证
    GetUserInfo({
      commit,
      state
    }) {
      return new Promise(async (resolve, reject) => {
        try {
          let token = getToken();
          let n = await loginApi.getUserInf(token);
          resolve(n.data);
        } catch (err) {
          reject(err);
        }
      })
    }
  },
  modules: {}
})